package com.shermanzhou.supergrpc;

import com.shermanzhou.supergrpc.model.GrpcMethodModel;
import com.shermanzhou.supergrpc.model.GrpcServiceModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Arrays;

/**
 * @author zhouchaoqun
 * @date 2018/12/6 下午6:28
 */
public class FreemarkerTest {
    public static void main(String[] args) throws Exception {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        File templateDir = new File(FreemarkerTest.class.getClassLoader().getResource("templates").toURI());
        cfg.setDirectoryForTemplateLoading(templateDir);
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        GrpcMethodModel methodModel = new GrpcMethodModel();
        methodModel.setMethodName("statisticsConsumption");
        methodModel.setRequestType("com.quancheng.aimee.model.quotamodel.StatisticsConsumptionRequest");
        methodModel.setResponseType("com.quancheng.aimee.model.quotamodel.StatisticsConsumptionResponse");

        GrpcServiceModel serviceModel = new GrpcServiceModel();
        serviceModel.setPackageName("com.quancheng.aimee.service");
        serviceModel.setServiceName("QuotaService");
        serviceModel.setMethods(Arrays.asList(methodModel));

        String packagePath = serviceModel.getPackageName().replace(".", "/");
        String dirPath = "demo-grpc/src/main/java/" + packagePath;
        File packageDir = new File(dirPath);
        packageDir.mkdirs();

        File serviceFile = new File(dirPath + "/QuotaService.java");
        File serviceImplFile = new File(dirPath + "/QuotaService_impl.java");
        File serviceServiceFile = new File(dirPath + "/QuotaService_service.java");

        Template template1 = cfg.getTemplate("service.ftl");
        Template template2 = cfg.getTemplate("service_impl.ftl");
        Template template3 = cfg.getTemplate("service_service.ftl");

        Writer out1 = new FileWriter(serviceFile);
        Writer out2 = new FileWriter(serviceImplFile);
        Writer out3 = new FileWriter(serviceServiceFile);
        template1.process(serviceModel, out1);
        template2.process(serviceModel, out2);
        template3.process(serviceModel, out3);
    }
}
